/**
 * Doc comments 4 goods_add
 * 忽略偶尔名为zz的临时变量和result等命名的全局变量
 * 以及30+的console.log
 * 以及关键处懒得写注释
 * @type {string}
 */

var classifyId = "";
//暂存规格名称
var tempSkuName = "";
//暂存规格值数组
var tempSkuValueArr = [];
//编辑状态暂存规格数组，包括现有和添加的tempSkuValueArr
var tempSkuValueArrAll = [];
//某分类下规格结果集合
var specResultList = [];

var result = [];//组合成产品集


$(document).ready(function () {
    //显示邮费方案选项
    showPostagePlans();
    //初始化表单验证，提交时触发
    $("#goodsAddForm").validate();

    $('.numbersOnly').keyup(function () {
        if (this.value != this.value.replace(/[^\0-9\.]/g, '')) {
            this.value = this.value.replace(/[^\0-9\.]/g, '');
        }
    });

    //产品线改变时，蜜雅阁商品无返现百分比
    $("#cateType").on("change", function () {
        var goodsType = $("#cateType").val();
        if (goodsType == 1) {
            $("#returnRateDiv").hide();
        } else $("#returnRateDiv").show();
    });

    $('#jstree_demo').on("select_node.jstree", function (e, data) {
        var instance = $('#jstree_demo').jstree(true);
        curCatePath = data.instance.get_path(data.selected[0], ">", 0);
        //获取当前选择目录路径
        console.log("selected的data数据", data.instance.get_path(data.selected[0], ">", 0));
        $("#curCatePath").text(curCatePath);
    });

    //初始化文件输入框
    initFileInput("file_upload", urlcore + "/api/attachment/upload", "#goodsUrl");
    //banner图图片地址
    initFileInput("fileupload2", urlcore + "/api/attachment/upload", "#picturesUrl");
    //视频地址
    initFileInput("fileupload3", urlcore + "/api/attachment/upload", "#videoUrl");
    //详情说明
    initMySummernote("goodsIntroduce");

    var id = getvl("id");
    if (id != undefined && id != "") {
        loadData(id);
    }
});

//弹出一个页面层
$('#addSpec').on('click', function () {
    $("#addProp").show();
});


//统一规格和多规格切换，0 为统一规格 1 为多规格
$(".ifUniformRadio").change(function () {
    var checkedRadioVal = $("input[name='ifUniformSpec']:checked").val();
    if (checkedRadioVal == "0")
        showUniformSpec();//统一规格

    if (checkedRadioVal == "1")
        showMultiSpec();//多规格
});

//展示统一规格
function showUniformSpec() {
    $("#addSpec").hide();
    $("#MultiSpec").hide();
    $("#UniformSpec").show();
}

//展示多规格
function showMultiSpec() {
    if (getClassifyId() == "" || getClassifyId() == undefined) {
        alert("请先选择商品分类！");
        //切回统一规格
        $("input[type='radio'][name='ifUniformSpec'][value='0']").prop("checked", "checked");
        return;
    }
    //如未选择分类，则提示先选择分类
    if (!noticeToSelectClassifyFirst()) {
        //切回统一规格
        $("input[type='radio'][name='ifUniformSpec'][value='0']").prop("checked", "checked");
        return;
    }
    $("#UniformSpec").hide();
    $("#addSpec").show();
    $("#MultiSpec").show();
    specResultList = getSpecList();
    result = [];
    $(".sku-table").html("");
    //移除原来的规格列表，重新生成
    $(".temp-sku").remove();
    combine(0, {});
    console.log("now specResultList:", specResultList);
    console.log("result:", result);

    var srIndex;
    for (srIndex of specResultList) {
        var tempSkuId = srIndex.id;
        tempSkuName = srIndex.attrName;
        var tempSkuValueArrAll = srIndex.propValues;
        for (var tsvIndex of tempSkuValueArrAll) {
            tempSkuValueArr.push(tsvIndex.propValue);
        }
        var skuTempHtml = getSkuTempHtml(tempSkuId, tempSkuName, tempSkuValueArrAll);
        $("#addProp").after(skuTempHtml);
        clearTemp();
    }
}


//显示数据(修改)
function loadData(id) {
    $('#jiu_picture_div').css("display", "block");
    $.ajax({
        type: "GET",
        url: urlcore + "/api/goods/goodsDetails?goodsId=" + id, //图片上传出来的url，返回的是图片上传后的路径，http格式
        dataType: "json",
        headers: {"Content-Type": "application/json;charset=UTF-8"},
        data: {},
        success: function (data) {//data是返回的hash,key之类的值，key是定义的文件名
            var da = data.data[0];
            if (data.success == true) {
                //处理规格和日期
                var unitPrices = " ";
                var marketPrices = " ";
                var unitStandards = " ";
                for (var i = 0; i < data.data.length; i++) {
                    unitPrices += data.data[i].unitPrice + ",";
                    marketPrices += data.data[i].marketPrice + ",";
                    unitStandards += data.data[i].unitStandard + ",";
                }
                marketPrices = (marketPrices.substring(marketPrices.length - 1) == ',') ? marketPrices.substring(0, marketPrices.length - 1) : marketPrices;
                unitStandards = (unitStandards.substring(unitStandards.length - 1) == ',') ? unitStandards.substring(0, unitStandards.length - 1) : unitStandards;
                unitPrices = (unitPrices.substring(unitPrices.length - 1) == ',') ? unitPrices.substring(0, unitPrices.length - 1) : unitPrices;

                $("#title").val(da.goods.title);
                $("#unitPrice").val(unitPrices);
                $("#marketPrice").val(marketPrices);
                $("#unitStandard").val(unitStandards);
                $("#goodsType").find("option[value='" + da.goods.goodsType + "']").prop("selected", true);//商品类型
                var goodsUrl = da.goods.goodsUrl, imgStr1 = "";
                if (goodsUrl != null && goodsUrl != '') {
                    goodsUrl = goodsUrl.split(",");
                    $.each(goodsUrl, function (index, value) {
                        imgStr1 +=
                            '<div style="position:relative;width:250px;height:250px;float:left;" display="block">' +
                            '	<span onclick="removeStrHtml(this)" style="position:absolute;top:10px;right:10px;font-size:20px;color:#f00;" class="glyphicon glyphicon-trash" aria-hidden="true">' +
                            '	</span>' +
                            '	<img style="padding: 5px 5px 5px 5px;" width="250px" height="250px" src="' + value + '">' +
                            '</div>';
                    });
                }
                $('#goodsUrl').html(imgStr1);
                $('#goodsIntroduce').summernote('code', da.goodsDetail.goodsIntroduce);
            } else {
                alert(data.msg);
            }
        },
        error: function () {
            alert("失败");
        }
    });
}


//表单提交
function onSave() {
    //如未选择分类，则提示先选择分类
    if (!noticeToSelectClassifyFirst())
        return;
    //表单校验
    if (!$("#goodsAddForm").valid()) return false;

    //获取是否统一规格单选框值
    var ifUniformSpec = $('input[type="radio"][name="ifUniformSpec"]:checked').val();
    // 多规格下sku价格和库存不能为空
    if (ifUniformSpec == 1) {
        var validateSku = $("#skuTable").find("input");
        var vlength = validateSku.length;
        for (var index = 0; index < vlength; index++) {
            if (validateSku[index].value == "") {
                alert("多规格下价格和库存不能为空");
                return;
            }
        }
    }

    // var id=getvl("id");
    var goodsType = $("#cateType").val();//产品线，商品类型（0 蜜哆哆 1蜜雅阁 2 品牌馆）
    var id = $("#id").val();
    var goodsName = $("#goodsName").val();
    //价格
    var mPrice = $("#mPrice").val();
    var otherPrice = $("#otherPrice").val();
    var returnRate = $("#returnRate").val() / 100;
    var returnRateY = $("#returnRateY").val() / 100;
    if (goodsType == 1) {
        returnRate = 0;
        returnRateY = 0;
    }


    // 主图片地址
    var goodsUrl = "";
    $("#goodsUrl img").each(function (index, item) {
        if (index == 0) {
            goodsUrl = $(this).attr("src");
        }
    });

    // banner组图图片地址
    var picturesUrl = "";
    $("#picturesUrl img").each(function (index, item) {
/*        if (index == 0) {
            goodsUrl = $(this).attr("src");
        }*/
        picturesUrl += $(this).attr("src") + ",";
    });
    if(""==goodsUrl||""==picturesUrl){
        alert("商品图片不能为空！");
        return;
    }
    if (picturesUrl != "") {
        picturesUrl = picturesUrl.substring(0, picturesUrl.length - 1);
    }
    // 详情视频地址
    var videoUrl;
    $("#videoUrl img").each(function (index, item) {
        if (index == 0) {
            videoUrl = $(this).attr("src");
        }
    });
    var onlineVideo = $("#onlineVideo").val();
    if (onlineVideo != "") {
        videoUrl = onlineVideo;
    }

    var goodsDetailId = $("#goodsDetailId").val();

    //详情介绍富文本
    /*    if(""==goodsIntroduce||undefined==goodsIntroduce){
           alert("详情介绍不能为空！");
           return;
       }*/
    if ($('#goodsIntroduce').summernote('isEmpty')) {
        alert("详情介绍不能为空！");
        return
    }
    var goodsIntroduce = $('#goodsIntroduce').summernote('code');
    var goodsRemarks = $("#goodsRemarks").val();

    //商品规格

    /*物流其他*/
    //获取邮费设置
    var postage = $('#postage option:selected').val();
    if(postage==undefined||postage==""){
        alert("邮费方案不能为空");
        return;
    }
    //邮费增加（超重超大等）
    var overDeliveryPostage = $("#overDeliveryPostage").val();
    //前端邮费显示名称
    var gtOnePostage = $("#gtOnePostage").val();
    //是否只有彩虹会员才能购买（0 体验会员和彩虹会员都可购买 1 彩虹会员才能购买）
    var rainbowOnly = $('input[type="radio"][name="rainbow_only"]:checked').val();
    //只上传，或直接发布
    var goodsStatus = $('input[type="radio"][name="goods_status"]:checked').val();
    // $("input[type='radio'][name='radio'][value='2']").prop("checked", "checked");// 设置value = 2的一项为选中

    //提交goods
    $.ajax({
        type: "POST",
        url: urlcore + "/api/goods/saveOrUpdate", //图片上传出来的url，返回的是图片上传后的路径，http格式
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify({
            // unitStandard: unitStandard,
            // status: 1,
            // goods: {
            id: id,
            goodsName: goodsName,
            classifyId: classifyId,
            mPrice: mPrice,
            otherPrice: otherPrice,
            returnRate: returnRate,
            returnRatey: returnRateY,
            goodsUrl: goodsUrl,
            goodsType: goodsType,
            postage: postage,
            overDeliveryPostage: overDeliveryPostage,
            gtOnePostage: gtOnePostage,
            rainbowOnly: rainbowOnly,
            goodsStatus: goodsStatus,
            // }
        }),
        success: function (data) {//data是返回的hash,key之类的值，key是定义的文件名
            if (data.success == true) {
                var goodsId = data.data.id;
                if (!goodsId) {
                    console.log("商品id不能为空！");
                    return;
                }

                //添加sku
                if (ifUniformSpec == "0") {
                    //统一规格时sku价格为商品价格
                    var uniformPrice = mPrice;
                    var uniformInventory = $("#uniformInventory").val();
                    $.ajax({
                        type: "POST",
                        url: urlcore + "/api/sku/addUniSku",
                        dataType: "json",
                        contentType: "application/json;charset=UTF-8",
                        data: JSON.stringify({
                            goodsId: goodsId,
                            // skuUrl: skuUrl,
                            price: uniformPrice,
                            inventory: uniformInventory,
                            ifUniformSpec: ifUniformSpec,
                            state: 1,//默认上传的商品状态为 1 在售

                        }),
                        success: function (data) {
                            alert("统一规格商品添加成功！");
                            window.location.href = "goods_list.html";
                        },
                        error: function () {

                        }
                    });
                }
                //多规格保存sku
                if (ifUniformSpec == "1") {
                    var skuList = [];
                    //sku
                    $(".sku-table > tbody tr").each(function () {
                        goodsId = goodsId;
                        //属性字符串
                        var propStr = $(this).find("td[class='td-sku-prop-str']").text();
                        //属性值组合
                        var valuesStr = $(this).find("td[class='td-sku-prop-values']").text();
                        //商品sku图片,选择器[attribute*='value']表示包含value值，并不一定全等
                        var skuUrl = $(this).find("div[class*='sku-url-div']").attr("data-url");
                        var price = $(this).find("input[name='sku_price']").val();
                        var inventory = $(this).find("input[name='sku_inventory']").val();
                        skuList.push({
                            goodsId: goodsId,
                            propStr: propStr,
                            valuesStr: valuesStr,
                            skuUrl: skuUrl,
                            price: price,
                            inventory: inventory,
                            ifUniformSpec: ifUniformSpec,
                            state: 1  //商品sku状态,1 在售 2 下架，默认新添加为在售
                        });
                    });

                    $.ajax({
                        type: "POST",
                        url: urlcore + "/api/sku/addSkuBatch",
                        dataType: "json",
                        contentType: "application/json;charset=UTF-8",
                        data: JSON.stringify(skuList),
                        success: function (data) {
                            alert("多规格商品添加成功！");
                            console.log("batchskudata", data);
                            window.location.href = "goods_list.html";
                        },
                        error: function () {

                        }
                    });

                }

                //添加详情
                $.ajax({
                    type: "POST",
                    url: urlcore + "/api/goodsDetail/saveOrUpdate",
                    dataType: "json",
                    contentType: "application/json;charset=UTF-8",
                    data: JSON.stringify({
                        id: goodsDetailId,
                        goodsId: goodsId,
                        videoUrl: videoUrl,
                        picturesUrl: picturesUrl,
                        goodsIntroduce: goodsIntroduce,
                        goodsRemarks: goodsRemarks,

                    }),
                    success: function (data) {

                    },
                    error: function () {

                    }
                });
                /*     if (id == "") {
                         if (confirm("添加成功，是否继续添加？")) {
                             //刷新
                             location.reload();
                         } else {
                             //跳转列表页
                             window.location.href = "goods_list.html?goodsType=" + goodsType;
                         }
                     } else {
                         alert("修改成功");
                         //跳转列表页
                         window.location.href = "goods_list.html?goodsType=" + goodsType;
                     }*/
                /*   } else if (data.code == 'OVERTIME') {
                       var thisUrl = window.location.href;
                       if (thisUrl.indexOf('login.html') <= -1) {
                           top.window.location.href = "login.html";
                       }*/
            } else {
                alert(data.msg);
            }
            console.log(data.data);
        },
        error: function (data) {
            alert("上传失败" + data.msg);
        }
    });
}

/**
 * 规格相关 begin
 */
//点击小×号移除某个已添加的规格值
$(".clearfix ").on("click", ".fa-remove", function () {
    if (!confirm("您删除的已有属性值可能影响到店铺中的其他商品规格"))
        return;
    //获取要删除的规格值，从暂存数组中删去
    var delTempPropValue = $(this).parent().parent().text();
    $(this).parent().parent().remove();
    //从暂存数组中删去
    tempSkuValueArr.splice(tempSkuValueArr.indexOf(delTempPropValue), 1);
});

function addTempSkuValue(event) {
    console.log(event.target.name);

    // console.log($(this).attr("name"));
}

//添加规格值
$("#btn_addTempSkuValue").on("click", function () {
        tempSkuName = $("#input-addSku-name").val();
        var tempSkuValue = $("#input-addSku-value").val();
        if (tempSkuName == "" || tempSkuValue == "") {
            alert("不能添加空规格！");
            return;
        }
        if (tempSkuValueArr.indexOf(tempSkuValue) >= 0) {
            alert("该规格值已存在！");
            return
        }
        tempSkuValueArr.push(tempSkuValue);
        $("#input-addSku-value").val("");
        var pid = "";
        var vid = ""
        //生成编辑状态的规格值html字符串
        var htmlstr = getAddEditTempHtmlStr(pid, vid, tempSkuValue);
        $("#addProp .clearfix").append(htmlstr);
    }
);

//生成编辑状态的规格值html字符串
function getAddEditTempHtmlStr(pid, vid, tempSkuValue) {
    var htmlstr = "<label class='label label-init' " +
        "data-pid='" + pid + "' data-vid='" + vid + "'>" +
        "<a class='ng-scope'><i class='fa fa-remove'></i></a>" +
        tempSkuValue +
        "</label>";
    return htmlstr;
}

function getEditTempHtmlStr(pid, vid, tempSkuValue) {
    var htmlstr = "<label class='label label-init' " +
        "data-pid='" + pid + "' data-vid='" + vid + "'>" +
        tempSkuValue +
        "</label>";
    return htmlstr;
}

//编辑某个规格
$("#MultiSpec").on("click", ".btn_editSku", function () {
    var editPid = $(this).prev().attr("data-pid");
    var editPname = $(this).prev().attr("data-pname");
    var tempPV = new Object();
    tempPV.editPid = editPid;
    var tempSkuValueArr = [];
    //编辑状态暂存规格数组，包括现有和添加的tempSkuValueArr,此时初始化为[]
    tempSkuValueArrAll = [];
    $(this).next().next().find("li").each(function () {
        var tempSkuValue = new Object();
        tempSkuValue.pid = $(this).find("input").attr("data-pid");
        tempSkuValue.vid = $(this).find("input").attr("data-vid");
        var temp = $(this).find("input").val();
        tempSkuValue.tempSkuValue = temp;
        //将编辑时当前已有规格值加入tempSkuValueArrAll数组中
        tempSkuValueArrAll.push(temp);
        console.log(tempSkuValue);
        tempSkuValueArr.push(tempSkuValue);
    });
    tempPV.tempSkuValueArr = tempSkuValueArr;
    var htmlstr = "";
    for (var zz of tempSkuValueArr) {
        htmlstr += getEditTempHtmlStr(zz.pid, zz.vid, zz.tempSkuValue);
    }
    //inject input-editSku-name's attributes contains editPid,editPname
    $("#input-editSku-name").val(editPname);
    $("#input-editSku-name").attr("editPid", editPid);
    $("#input-editSku-name").attr("editPname", editPname);
    $("#editSpanPname").text(editPname);
    $("#editProp .clearfix").html("")
    //生成当前待编辑规格值
    $("#editProp .clearfix").append(htmlstr);
    //显示编辑窗口
    $(".edit-whole-div").show();
    // generateSpecEditHtml();
});


//编辑规格的添加规格值
$("#btn_addEditTempSkuValue").on("click", function () {
    tempSkuName = $("#input-editSku-name").val();
    var tempSkuValue = $("#input-editSku-value").val();
    if (tempSkuName == "" || tempSkuValue == "") {
        alert("不能添加空规格！");
        return;
    }

    if (tempSkuValueArrAll.indexOf(tempSkuValue) >= 0) {
        alert("该规格值已存在！");
        return
    }
    tempSkuValueArrAll.push(tempSkuValue);
    tempSkuValueArr.push(tempSkuValue);
    $("#input-editSku-value").val("");
    var pid = "";
    var vid = ""
    //生成编辑状态的规格值html字符串
    var htmlstr = getEditTempHtmlStr(pid, vid, tempSkuValue);
    $("#editProp .clearfix").append(htmlstr);

});

//编辑添加规格保存
$("#btn_EditSku").on("click", function () {
    $(".edit-whole-div").show();
    var editPid = $("#input-editSku-name").attr("editpid");
    if (tempSkuValueArr.length == 0)
        return;
    var propValueList = [];
    for (var zz of tempSkuValueArr) {
        propValueList.push({
            propValue: zz,
            propNameId: editPid,
        });
    }
    $.ajax({
        type: "POST",
        url: urlcore + "/api/propValue/addPropValueBatch",
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(propValueList),
        success: function (cbdata) {
            var skuTempHtml = "";
            for (var zz of cbdata.data) {
                skuTempHtml +=
                    '<li>' +
                    '<label>' +
                    '    <input type=\"checkbox\" class=\"sku_value\" data-pid="' + zz.propNameId + '" data-vid=\"' + zz.id + '\" value=\"' + zz.propValue + '\" />' +
                    zz.propValue +
                    '</label>' +
                    '</li>';
            }
            $("#MultiSpec").find('input[class*="sku_value"][data-pid="' + zz.propNameId + '"]')
                .last().parent().parent().after(skuTempHtml);
            /* cbdata.data形如
             0:{id: 79, propValue: "11", propName: null, propNameId: 24, gmtDatetime: "2017-09-07 11:28:00", …}
             1:{id: 80, propValue: "22", propName: null, propNameId: 24, gmtDatetime: "2017-09-07 11:28:00", …}*/
            console.log("规格值添加成功");
            console.log("batchpropvaluedata", cbdata);
            tempSkuValueArr = [];
            tempSkuValueArrAll = [];
            $("#editSpanPname").text("");
            $("#input-editSku-name").val("");
            $("#editProp .clearfix").html("");
            $(".edit-whole-div").hide();


        },
        error: function () {
            alert("编辑时添加规格值失败");
        }
    });
});

//取消编辑
function cancelEditSku() {
    tempSkuValueArr = [];
    tempSkuValueArrAll = [];
    $("#editSpanPname").text("");
    $("#input-editSku-name").val("");
    $("#editProp .clearfix").html("");
    $(".edit-whole-div").hide();
}

//删除某个规格,先警告,后刷新规格列表和sku列表
$("#MultiSpec").on("click", ".btn_delSku", function () {
    if (!confirm("删除可能会造成该类下其他商品(未处理订单)的商品规格出现错误！！！确认删除吗？"))
        return;
    var delPropNameId = $(this).prev().prev().attr("data-pid");
    $(this).parent().remove();
    //根据规格名称id删除某规格（包括规格值）
    $.ajax({
        type: "GET",
        url: urlcore + "/api/sku/delProp",
        dataType: "json",
        async: false,//禁止异步
        contentType: "application/json;charset=UTF-8",
        data: {propId: delPropNameId},
        success: function (data) {
        },
        error: function () {

        }
    });
    //获取当前分类下规格集合
    specResultList = getSpecList();
    /*    if (specResultList != null && specResultList.length > 0) {
            result = [];
            //做规格笛卡尔积，转化规格为多个sku
            combine(0, {});
            console.log("now specResultList:", specResultList);
            console.log("result:", result);
            //生成sku表格
            generateSkuTable(result);
        }*/
});


//添加规格,via web to DB
$("#btn_addSku").on("click", function () {
    tempSkuName = $("#input-addSku-name").val();
    //如未选择分类，则提示先选择分类
    noticeToSelectClassifyFirst();
    if (tempSkuName == "" || tempSkuValueArr.length == 0) {
        alert("不能添加空规格！");
        return;
    }
    var skuMapItem = new Object();
    skuMapItem.classifyId = classifyId;
    skuMapItem.prop_name = tempSkuName;
    skuMapItem.prop_value = tempSkuValueArr;
    $.ajax({
        type: "POST",
        url: urlcore + "/api/sku/addProp",
        dataType: "json",
        contentType: "application/json;charset=UTF-8",
        data: JSON.stringify(skuMapItem),
        success: function (data) {
            console.log(data);
            var propValueList = data.data.propValueList;
            /* 形如
             0:{id: 49, propValue: "3", propName: null, propNameId: 21, gmtDatetime: null, …}
             1:{id: 50, propValue: "4", propName: null, propNameId: 21, gmtDatetime: null, …}*/
            var skuTempHtml = getSkuTempHtml(data.data.propName.id, tempSkuName, propValueList);
            $("#addProp").after(skuTempHtml);
            //初始化添加规格框
            $("#addProp input").val("");
            $("#addProp .clearfix").html("");
            //清空暂存数据
            clearTemp();

            //获取当前分类下规格集合
            specResultList = getSpecList();
            /*     if (specResultList != null && specResultList.length > 0) {
                     result = [];
                     //做规格笛卡尔积，转化规格为多个sku
                     combine(0, {});
                     console.log("now specResultList:", specResultList);
                     console.log("result:", result);
                     //生成sku表格
                     generateSkuTable(result);
                 }*/
        },
        error: function () {
            alert("添加规格失败！");
        }
    });

});


//取消添加规格
function cancelAddSku() {
    $("#input-addSku-name").val("");
    $("#input-addSku-value").val("");
    $("#addProp .clearfix").html("");//清除已添加规格值
}


//返回html字符串，添加一组可选规格到页面
function getSkuTempHtml(tempSkuId, tempSkuName, propValueList) {
    /* 形如
            0:{id: 49, propValue: "3", propName: null, propNameId: 21, gmtDatetime: null, …}
            1:{id: 50, propValue: "4", propName: null, propNameId: 21, gmtDatetime: null, …}*/
    var skuTempHtml = '<div  class="SKU_TYPE sku-list item temp-sku">' +
        '<span data-pid=\"' + tempSkuId + '\" data-pname=\"' + tempSkuName + '\">' +
        tempSkuName +
        '</span>' +
        '<a class="btn_editSku btn btn-inline btn-sm ">编辑</a>' +
        '<a class="btn_delSku btn btn-inline btn-sm "' +
        'placement="right" maximize="true">删除</a>' +
        '<ul class="sku-tree">';
    var tv;
    for (tv in propValueList) {
        var p_id = propValueList[tv].propNameId;
        var v_id = propValueList[tv].id;
        var v_value = propValueList[tv].propValue;
        skuTempHtml +=
            '<li >' +
            '<label>' +
            '    <input type=\"checkbox\" class=\"sku_value\" data-pid="' + p_id + '" data-vid=\"' + v_id + '\" value=\"' + v_value + '\" />' +
            v_value +
            '</label>' +
            '</li>'
    }
    skuTempHtml += '</ul>' + '</div>';
    return skuTempHtml;
}

//生成sku表格,参数result为转化后的sku数组
function generateSkuTable(result) {
    if (result == null || result == undefined || result.length == 0)
        return;
    $(".sku-table").html("");
    //获取其下属性数组，举例格式为["大小", "容量", "颜色"]
    var propArr = Object.getOwnPropertyNames(result[0]).sort();
    console.log("propArr:", propArr);
    var skuTheadStr = "<thead>\n" +
        "                                                <tr>\n" +
        "                                                    <td class=\"thead-sku-id\" style=\"display: none\"></td>\n";
    for (var prop_p of propArr) {
        skuTheadStr += "<td class=\"thead-prop-name\">" + prop_p + "</td>\n";
    }
    skuTheadStr += "<td class=\"thead-sku-prop-str\" style=\"display: none\"></td>\n" +
        "<td class=\"thead-sku-prop-values\" style=\"display: none\"></td>\n" +
        "                                                    <td>商品图片</td>\n" +
        "                                                    <td>价格</td>\n" +
        "                                                    <td>库存</td>\n" +
        "                                                    <td width=\"80\">删除操作</td>\n" +
        "                                                </tr>\n" +
        "                                                </thead>";
    $(".sku-table").append(skuTheadStr);
    var skuTbodyStr = "        <tbody>\n";
    var tempSku = [];
    var zz = 0;
    console.log("result array for generate table:", result);
    for (tempSku of result) {
        zz++;
        skuTbodyStr += "<tr class=\"js-sku-content\">\n";
        skuTbodyStr += "<td class=\"td-sku-id\" style=\"display: none\"></td>\n";
        console.log(tempSku);
        var str = "";
        //要存储的属性字符串
        var prop_str = "";
        //要存储的属性值名组合（订单显示用）
        var prop_values = "";
        for (var prop_p of propArr) {
            var prop_pid = tempSku[prop_p].propNameId;
            var prop_vid = tempSku[prop_p].id;
            var prop_v = tempSku[prop_p].propValue;
            str += prop_p + ":" + prop_v + "::" + prop_pid + "-" + prop_vid + ",";
            prop_str += prop_pid + "-" + prop_vid + ",";
            prop_values += "、" + prop_v;
            skuTbodyStr += "<td class=\"td-prop-value\">" + prop_v + "</td>\n";
        }
        prop_values = prop_values.substr(1);
        console.log(str);
        console.log(prop_str);
        console.log(prop_values);
        var skuUrl = "";
        skuTbodyStr += "<td class=\"td-sku-prop-str\" style=\"display: none\">" + prop_str + "</td>\n" +
            "<td class=\"td-sku-prop-values\" style=\"display: none\">" + prop_values + "</td>\n" +
            " <td class=\"sku-url\" data-url=\"" + skuUrl + "\">" +
            "<div id='dz" + zz + "' data-url=\"\" class=\"sku-url-div dropzone\" name=\"file\">\n" +
            "                                    <div id='pr" + zz + "' class=\"dropzone-previews drop-preview\"></div>\n" +
            "                                    <a class=\"upload_sku_pic btn btn-inline btn-sm dz-message drop-a\">上传图片</a>\n" +
            "                                </div>" +
            "</td>" +
            "                                                    <td>\n" +
            "                                                        <div class=\"validator-form\">\n" +
            "                                                            <input custom-number=\"\" decimal=\"2\"\n" +
            "                                                                   class=\"form-control input-sm sku-price-input ng-pristine ng-untouched ng-isolate-scope ng-invalid ng-invalid-custom-number\"\n" +
            "                                                                   type=\"text\" name=\"sku_price\" value=\"\"\n" +
            "                                                                   style=\"\"></div>\n" +
            "                                                    </td>\n" +
            "                                                    <td>\n" +
            "                                                        <div class=\"validator-form\">\n" +
            "                                                            <input custom-number=\"\"\n" +
            "                                                                   class=\"form-control input-sm sku-stock-input ng-pristine ng-untouched ng-isolate-scope ng-invalid ng-invalid-custom-number\"\n" +
            "                                                                   type=\"text\" name=\"sku_inventory\" value=\"\"\n" +
            "                                                                   style=\"\"></div>\n" +
            "                                                    </td>\n" +
            "                                                    <td class=\"remove-a-sku\"><a placement=\"bottom\"\n" +
            "                                                                                maximize=\"true\"><i\n" +
            "                                                            class=\"fa fa-remove\"></i></a>\n" +
            "                                                    </td>\n" +
            "                                                </tr>\n";
    }
    skuTbodyStr += "</tbody>";
    $(".sku-table").append(skuTbodyStr);

    $(".sku-table input").validate();
    //为表格中每个图片上传处初始化dropzone设置
    initTableDropzone();
}

//初始化dropzone设置
function initTableDropzone() {
    //遍历result，为表格的每行的图片上传初始化，也可以改成遍历表格进行初始化
    for (var i = 1; i <= result.length; i++) {
        //对应生成的dropzone div的id和previewsContainer的id
        var dzid = '#dz' + i;
        var prid = '#pr' + i;
        Dropzone.autoDiscover = false;//解决两次实例Dropzone错误，可在控制台看到该错误
        $(dzid).dropzone({
            url: urlcore + "/api/attachment/upload",
//                                        paramName: "skuUrl", // The name that will be used to transfer the file
            maxFiles: 1,
            thumbnailWidth: 100,
            thumbnailHeight: 100,
            addRemoveLinks: true,//清除图片
            dictRemoveFile: "删除图片",//如果addRemoveLinks为 true，这段文本用来设置删除文件显示文本.
            dictCancelUpload: "取消上传",//如果addRemoveLinks为 true，这段文本用来设置取消上载链接的文本
            previewsContainer: prid, // 文件预览显示位置,可以为id或class选择器或html元素
            success: function (file, data) {
                //这里的$(this)其实得到的是Dropzone对象（对象数组，取第一个为当前Dropzone对象）
                console.log($(this));
                //通过查看Dropzone对象的结构得到对应div的id
                var sku_url_id = '#' + $(this)[0].element.id;
                console.log("file:", file);
                console.log("data:", data);
                var skuUrl = data.data[0];
                console.log("sku-url:", skuUrl);
                //为div中的data-url属性赋值
                $(sku_url_id).attr("data-url", skuUrl);
                //隐藏上传图片按钮
                $(sku_url_id).find('a[class*="upload_sku_pic"]').hide();
            },
            init: function () {
                this.on("addedfile", function (file) {
                    console.log("addedfile");// actions...
                });
                this.on("removedfile", function (file) {
                    //通过$(this)对象（Dropzone对象）得到当前div的id
                    var cur_skudiv_id = '#' + $(this)[0].element.id;
                    /*移除图片时显示上传图片按钮*/
                    $(cur_skudiv_id).find('a[class*="upload_sku_pic"]').show();
                    console.log("removedfile");// actions...
                });
            },
        });
    }

}

//获取分类树当前选中分类
function getClassifyId() {
    var instance = $('#jstree_demo').jstree(true);
    classifyId = instance.get_selected()[0]
    return classifyId;
}

//获取规格集合
function getSpecList() {
    //如未选择分类，则提示先选择分类
    noticeToSelectClassifyFirst();
    $.ajax({
        type: "GET",
        url: urlcore + "/api/sku/selectSpecListByClassifyId",
        dataType: "json",
        async: false,//禁止异步
        contentType: "application/json;charset=UTF-8",
        data: {classifyId: classifyId},
        success: function (data) {
            specResultList = data.data;
            console.log("specResultList:", specResultList);
        },
        error: function () {

        }
    });
    return specResultList;
}

//清除暂存数据
function clearTemp() {
    //清空暂存数组
    tempSkuName = "";
    tempSkuValueArr = [];
}

//提示先选择具体分类
function noticeToSelectClassifyFirst() {
    classifyId = getClassifyId();
    var instance = $('#jstree_demo').jstree(true);
    if (classifyId == "" || classifyId == undefined || instance.get_parent(classifyId) == "#") {
        alert("请先选择具体的二级或三级商品分类！");
        return false;
    }
    else return true;
}

//删除表格中某个不需要的sku
$(".sku-table").on("click", ".fa-remove", function () {
    if (!confirm("确定删除该规格吗？"))
        return;
    $(this).parent().parent().parent().remove();
});


//根据规格集合生成sku笛卡尔积
function combine(index, current) {
    if (index < specResultList.length - 1) {
        var specItem = specResultList[index];
        var keya = specItem.attrName;
        var items = specItem.propValues;
        if (items.length == 0) {
            combine(index + 1, current);
        }
        for (var i = 0; i < items.length; i++) {
            if (!items[i]) continue;
            var newMap = {};
            newMap = $.extend(newMap, current);
            newMap[keya] = items[i];
            combine(index + 1, newMap);
        }

    } else if (index == specResultList.length - 1) {
        var specItem = specResultList[index];
        var keya = specItem.attrName;
        var items = specItem.propValues;
        if (items.length == 0) {
            result.push(current);
        }
        for (var i = 0; i < items.length; i++) {
            if (!items[i]) continue;
            var newMap = {};
            newMap = $.extend(newMap, current);
            newMap[keya] = items[i];
            result.push(newMap);
        }
    }
}


//表格创建
$(document).on("change", '.sku_value', function () {
    var skuTypeArr = [];//存放SKU类型的数组
    var totalRow = 1;//总行数
    //获取所选规格数组
    skuTypeArr = getCkeckedSkuTypeArr(skuTypeArr, totalRow);

    /* skuTypeArr结果形如
     0:{attrName: "试试", propNameId: "26", propValues: Array(1), skuValueLen: 1}
     1:{attrName: "你好", propNameId: "24", propValues: Array(1), skuValueLen: 1}*/
    if (skuTypeArr.length == 0) {
        $(".sku-table").html("");
    } else {
        //已选规格集合
        specResultList = skuTypeArr;
        result = [];
        //做规格笛卡尔积，转化规格为多个sku
        generate(0, {});
        //生成sku表格
        generateSkuTable(result);
    }
});

function getCkeckedSkuTypeArr(skuTypeArr, totalRow) {
    //获取所选规格数组
    $(".SKU_TYPE").each(function () {
        //SKU类型节点
        var skuTypeNode = $(this).children("span");
        var skuTypeObj = {};//sku类型对象
        //SKU属性类型标题
        skuTypeObj.attrName = $(skuTypeNode).attr("data-pname");
        //SKU属性类型主键
        var propid = $(skuTypeNode).attr("data-pid");
        skuTypeObj.propNameId = propid;
        skuValueArr = [];//存放SKU值的数组
        //SKU相对应的节点
        var skuValNode = $(this).find('ul[class="sku-tree"]');
        //获取SKU值
        var skuValCheckBoxs = $(skuValNode).find("input[type='checkbox'][class*='sku_value']");
        var checkedNodeLen = 0;//选中的SKU节点的个数
        $(skuValCheckBoxs).each(function () {
            if ($(this).is(":checked")) {
                var skuValObj = {};//SKU值对象
                skuValObj.propValue = $(this).val();
                skuValObj.id = $(this).attr("data-vid");
                skuValObj.propNameId = propid;
                skuValueArr.push(skuValObj);
                checkedNodeLen++;
            }
        });
        if (skuValueArr && skuValueArr.length > 0) {
            totalRow = totalRow * skuValueArr.length;
            skuTypeObj.propValues = skuValueArr;//sku值数组
            skuTypeObj.skuValueLen = skuValueArr.length;//sku值长度
            skuTypeArr.push(skuTypeObj);//保存进数组中
        }
    });
    return skuTypeArr;
}

//根据规格集合生成sku笛卡尔积
function generate(index, current) {
    if (index < specResultList.length - 1) {
        var specItem = specResultList[index];
        var keya = specItem.attrName;
        var items = specItem.propValues;
        if (items.length == 0) {
            generate(index + 1, current);
        }
        for (var i = 0; i < items.length; i++) {
            if (!items[i]) continue;
            var newMap = {};
            newMap = $.extend(newMap, current);
            newMap[keya] = items[i];
            generate(index + 1, newMap);
        }

    } else if (index == specResultList.length - 1) {
        var specItem = specResultList[index];
        var keya = specItem.attrName;
        var items = specItem.propValues;
        if (items.length == 0) {
            result.push(current);
        }
        for (var i = 0; i < items.length; i++) {
            if (!items[i]) continue;
            var newMap = {};
            newMap = $.extend(newMap, current);
            newMap[keya] = items[i];
            result.push(newMap);
        }
    }
}


//测试
function test() {

    var validateSku = $("#skuTable").find("input");
    var vlength = validateSku.length;
    for (var index = 0; index < vlength; index++) {
        if (validateSku[index].value == "") {
            alert("多规格下价格和库存不能为空");
            return;
        }
    }
    console.log("validateSku", validateSku);
    //表单校验
    if (!$(".sku-table input").valid()) {
        alert("must not null");
        return;
    }
    var goodsUrl = "";
    // banner组图图片地址
    var picturesUrl = "";
    $("#picturesUrl img").each(function (index, item) {
        if (index == 0) {
            goodsUrl = $(this).attr("src");
        }
        picturesUrl += $(this).attr("src") + ",";
    });

    var onlineVideo = $("#onlineVideo").val();

    // postage=$("#postage").val;
    var postage = "";
    postage = $('#postage option:selected').val();
    var goodsStatus = $('input[type="radio"][name="goods_status"]:checked').val();
    var uniformPrice = $("#mPrice").val();
    console.log("goodsUrl:", goodsUrl);
    console.log("picturesUrl:", picturesUrl);
    console.log("onlineVideo:", onlineVideo);
    console.log("postage:", postage);
    console.log("goodsStatus:", goodsStatus);
    console.log("uniformPrice:", uniformPrice);
    console.log("主图地址:", picturesUrl);
    var goodsIntroduce = $('#goodsIntroduce').summernote('code');
    $("#preview").html(goodsIntroduce);
    $("#preview").addClass("resizable");

    //sku
    $(".sku-table > tbody tr").each(function () {
        var propStr = $(this).find("td[class='td-sku-prop-str']").text();
        console.log($(this).find("div[class*='sku-url-div']"));
        //商品sku图片
        var skuUrl = $(this).find("div[class*='sku-url-div']").attr("data-url");
        var price = $(this).find("input[name='sku_price']").val();
        var inventory = $(this).find("input[name='sku_inventory']").val();
        console.log("propStr:", propStr);
        console.log("skuUrl:", skuUrl);
        console.log("price:", price);
        console.log("inventory:", inventory);
    });
}

//显示邮费方案
function showPostagePlans() {
    $.ajax({
        url: urlcore + "/api/deliveryPlan/getGoodsAddChosenPlans",
        method: "get",
        dataType: "json",
        // async: false,//禁止异步
        contentType: "application/json;charset=UTF-8",
        success: function (data) {
            console.log(data.data);
           var items = data.data;
           if(items.length>0){
               //生成选择邮费方案的opt
               generateOptHtml(items);
           }
        },
        error: function (data) {
            alert("获取方案失败");
        }
    });
}

//生成选择分组的optgroup
function generateOptHtml(items) {
    var htmlStr ="";
    //生成optgroup
    for (var item of items) {
        htmlStr += "<option value=\"" + item.num + "\">" + item.title + "</option>";
    }
    $("#postage").append(htmlStr);
}